package com.yx.cloud.product.laser.yxcloud;

import android.content.Intent;
import android.util.Log;

import com.google.gson.Gson;
import com.iot.common.utils.Event;
import com.iot.common.utils.LogUtils;
import com.iot.common.utils.StringUtils;
import com.iot.product.sweeper.bean.Appointment;
import com.iot.product.sweeper.bean.CleanParam;
import com.iot.product.sweeper.bean.QuietHour;
import com.iot.product.sweeper.bean.Robot;
import com.iot.product.sweeper.bean.RobotStatus;
import com.iot.product.sweeper.bean.RoomCleanParam;
import com.iot.sweeper.param.MapNameParam;
import com.yx.cloud.AppStatusConstant;
import com.yx.cloud.constant.Constants;
import com.yx.cloud.product.laser.tuyapublic.ParseResult;
import com.yx.cloud.product.laser.tuyapublic.TuyaLaserConstant;
import com.yx.cloud.product.laser.tuyapublic.TuyaPublicMapDataParser;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class YxCloudLaserDataConverter {
    private final static String TAG = "YxCloudLaserDataConverter";

    public static void parseDp(Robot robot, JSONObject dps) {
        if (AppStatusConstant.coundownIgnoreStateCount()) {
            return;
        }
        initRobotData(robot, dps);
    }

    private static void initRobotData(Robot robot, JSONObject jsonObject) {
        LogUtils.i("aaaaaaaaaa 公版 DPParser dps: " + jsonObject);
        try {
            if (jsonObject.has(TuyaLaserConstant.SWITCH_GO)) {
                //清扫开关 true：清扫启动 false：清扫停止
                boolean isSweeping = jsonObject.getBoolean(TuyaLaserConstant.SWITCH_GO);
            }
            if (jsonObject.has(TuyaLaserConstant.PAUSE)) {
                //工作模式true：暂停当前工作状态 false：继续当前工作状态
                boolean mode = jsonObject.getBoolean(TuyaLaserConstant.PAUSE);
            }
            if (jsonObject.has(TuyaLaserConstant.SWITCH_CHARGE)) {
                //回充开关true：回充启动false：回充停止
                String mode = jsonObject.getString(TuyaLaserConstant.SWITCH_CHARGE);
            }
            if (jsonObject.has(TuyaLaserConstant.MODE)) {
                //工作模式默认值（不可修改删除，否则影响控制面板逻辑）：
                //smart - 自动清扫模式/全屋清扫模式
                //chargego - 自动回充模式（需要兼容：goto_charge）
                //zone - 划区清扫模式/矩形清扫模式
                //pose - 指哪扫哪模式/定点清扫模式
                //part - 局部清扫模式
                //select_room - 选区清扫模式
                int workMode = robot.getRobotStatus().getWorkMode();
                int clean_mode = Integer.parseInt(jsonObject.getString(TuyaLaserConstant.MODE));
                if (0 == clean_mode) {
                    //全局清扫
                    workMode = RobotStatus.MODE_AUTO_CLEAN;
                } else if (2 == clean_mode) {
                    //指哪扫哪(定点扫)
                    workMode = RobotStatus.MODE_SPOT_CLEAN;//定点清扫
                } else if (1 == clean_mode) {
                    //区域扫
                    workMode = RobotStatus.MODE_CUSTOM_CLEAN;
                } else if (4 == clean_mode) {
                    //回充
                    workMode = RobotStatus.MODE_RECHARGE;
                } else if (6 == clean_mode) {
                    //选区清扫
                    workMode = RobotStatus.MODE_ROOM_CLEAN;//按房间清扫
                } else if (3 == clean_mode) {
                    //局部清扫
                    workMode = RobotStatus.MODE_SPOT_CLEAN;//局部清扫
                } else if (5 == clean_mode) {
                    //沿墙
                    workMode = RobotStatus.MODE_EDGE_CLEAN;//沿墙清扫
                }
                // robot.getRobotStatus().setWorkState(RobotStatus.STATE_WORKING);//状态有延时，这时取到的还是上次的状态，就出现状态模式不匹配的问题
                robot.getRobotStatus().setWorkMode(workMode);
            }

            if (jsonObject.has(TuyaLaserConstant.STATUS)) {
                int robot_state = Integer.parseInt(jsonObject.getString(TuyaLaserConstant.STATUS));
                parseState(robot_state, robot);
            }
            if (jsonObject.has(TuyaLaserConstant.CLEAN_TIME)) {
                ///实时 清扫时间
                int clean_time = jsonObject.getInt(TuyaLaserConstant.CLEAN_TIME);
                robot.getCleanStatistics().setCleanTime((int) clean_time);
                Event.newBuilder().type(Event.MESSAGE_TYPE_CLEAN_AREA_DURATION).send();
            }
            if (jsonObject.has(TuyaLaserConstant.CLEAN_AREA)) {
                ///实时 清扫面积
                int clean_area = jsonObject.getInt(TuyaLaserConstant.CLEAN_AREA);
                robot.getCleanStatistics().setCleanArea((int) clean_area);
                Event.newBuilder().type(Event.MESSAGE_TYPE_CLEAN_AREA_DURATION).send();
            }

            if (jsonObject.has(TuyaLaserConstant.RESIDUAL_ELECTRICITY)) {
                //电量
                int battery = jsonObject.getInt(TuyaLaserConstant.RESIDUAL_ELECTRICITY);
                robot.getRobotStatus().setBattery(battery);
                Event.newBuilder().type(Event.MSG_ROBOT_STATE_POWER).content(battery).send();
                //低电量
                if (battery < 20) {
                    Event.newBuilder().type(Event.MSG_ROBOT_STATE_LOW_POWER).content(battery).send();
                } else {
                    Event.newBuilder().type(Event.MSG_ROBOT_STATE_HEALTH_POWER).content(battery).send();
                }
            }
            if (jsonObject.has(TuyaLaserConstant.SUCTION)) {
                //吸力 closed - 关闭 gentle - 安静 normal - 正常 strong - 强劲 max - 超强
                int suction = Integer.parseInt(jsonObject.getString(TuyaLaserConstant.SUCTION));
                robot.getCleanSettings().setSuction(suction);
                Event.newBuilder().result(true).type(Event.MESSAGE_TYPE_SUCTION_STATUS).content(suction).send();
            }
            if (jsonObject.has(TuyaLaserConstant.CISTERN)) {
                //水量 closed - 关闭 low - 低 middle - 中 high - 高
                int water_mode = Integer.parseInt(jsonObject.getString(TuyaLaserConstant.CISTERN));
                //获取水量设置
                robot.getCleanSettings().setMopHumidity(water_mode);
                Event.newBuilder().result(true).type(Event.MESSAGE_TYPE_WATER_STATUS).content(water_mode).send();
            }
            if (jsonObject.has(TuyaLaserConstant.COMMAND_TRANS)) {
                String strData = jsonObject.getString(TuyaLaserConstant.COMMAND_TRANS);
                byte[] bytes = StringUtils.hexToByte(strData);
                List<byte[]> data = YxCloudMapDataParser.getCmdAndData(bytes);
                if (data != null && data.size() > 0) {
                    for (int i = 0; i < data.size(); i++) {
                        byte cmd = data.get(i)[0];
                        byte[] dst = new byte[data.get(i).length - 1];
                        System.arraycopy(data.get(i), 1, dst, 0, dst.length);
                        ParseResult result;
                        switch (cmd) {
                            case 0x51://虚拟墙设置上报
                                Log.d(TAG, "aaaaaaaaaa 虚拟墙设置上报");
                                if (dst[0] == 0x01) {
                                    Log.d(TAG, "aaaaaaaaaa 虚拟墙设置上报成功");
                                    Event.newBuilder().type(Event.MESSAGE_TYPE_SET_AREA_SUCCESS).result(true).content(robot.getMap().getArea()).send();
                                }
                                if (dst[0] == 0x00) {
                                    Log.d(TAG, "aaaaaaaaaa 虚拟墙设置上报失敗");
                                    Event.newBuilder().type(Event.MESSAGE_TYPE_SET_AREA_FAIL).result(false).send();
                                }
                                break;
                            case 0x15://选区清扫上报
                                break;
                            case 0x17://定点清扫上报
                                break;
                            case 0x52://禁区设置上报
                                Log.d(TAG, "aaaaaaaaaa 禁区设置上报");
                                if (dst[0] == 0x01) {
                                    Log.d(TAG, "aaaaaaaaaa 禁区设置上报成功");
                                    Event.newBuilder().type(Event.MESSAGE_TYPE_SET_AREA_SUCCESS).result(true).content(robot.getMap().getArea()).send();
                                }
                                if (dst[0] == 0x00) {
                                    Log.d(TAG, "aaaaaaaaaa 禁区设置上报失敗");
                                    Event.newBuilder().type(Event.MESSAGE_TYPE_SET_AREA_FAIL).result(false).send();
                                }
                                break;
                            case 0x1D://房间分割上报
                                Log.d(TAG, "aaaaaaaaaa 房间分割上报");
                                if (dst[0] == 0x01) {
                                    Log.d(TAG, "aaaaaaaaaa 房间分割成功");
                                    Event.newBuilder().type(Event.MESSAGE_TYPE_DIVIDE_AREA_SUCCESS).result(true).send();
                                }
                                if (dst[0] == 0x00) {
                                    Log.d(TAG, "aaaaaaaaaa 房间分割失敗");
                                    Event.newBuilder().type(Event.MESSAGE_TYPE_DIVIDE_AREA_FAIL).result(true).send();
                                }
                                if (dst[0] == 0x02) {
                                    Log.d(TAG, "aaaaaaaaaa 分割失败（达到分区数量限制)");
                                    Event.newBuilder().type(Event.MESSAGE_TYPE_DIVIDE_AREA_FAIL).result(true).send();
                                }
                                if (dst[0] == 0x03) {
                                    Log.d(TAG, "aaaaaaaaaa 分割失败（分区面积过小）");
                                    Event.newBuilder().type(Event.MESSAGE_TYPE_DIVIDE_AREA_FAIL).result(true).send();
                                }
                                break;
                            case 0x1F://房间合并上报
                                Log.d(TAG, "aaaaaaaaaa 房间合并上报");
                                if (dst[0] == 0x01) {
                                    Log.d(TAG, "aaaaaaaaaa 房间合并成功");
                                    Event.newBuilder().type(Event.MESSAGE_TYPE_MERGE_AREA_SUCCESS).result(true).send();
                                }
                                if (dst[0] == 0x00) {
                                    Log.d(TAG, "aaaaaaaaaa 房间合并失敗");
                                    Event.newBuilder().type(Event.MESSAGE_TYPE_MERGE_AREA_FAIL).result(false).send();
                                }
                                if (dst[0] == 0x02) {
                                    Log.d(TAG, "aaaaaaaaaa 房间不相邻");
                                    Event.newBuilder().type(Event.MESSAGE_TYPE_TWO_ROOM_CAN_NOT_REACH).result(true).send();
                                }
                                if (dst[0] == 0x03) {
                                    Log.d(TAG, "aaaaaaaaaa 合并后的房间面积太大");
                                    Event.newBuilder().type(Event.MESSAGE_TYPE_MERGE_AREA_FAIL).result(true).send();
                                }
                                break;
                            case 0x21://房间分区恢复默认上报
                                if (dst[0] == 0x01) {
                                    Log.d(TAG, "aaaaaaaaaa 房间分区恢复默认成功");
                                    Event.newBuilder().type(Event.MESSAGE_TYPE_RESET_ROOM_SUCCESS).result(true).send();
                                }
                                if (dst[0] == 0x00) {
                                    Log.d(TAG, "aaaaaaaaaa 房间分区恢复默认失敗");
                                    Event.newBuilder().type(Event.MESSAGE_TYPE_RESET_ROOM_FAIL).result(false).send();
                                }
                                break;
                            case 0x23://定制模式保存上报
                                result = YxCloudMapDataParser.parseCustomInfoData(robot.getMap().getRoom(), dst);
                                if (result.getCode() == ParseResult.MSG_PARSE_SUCCESS) {
                                    Event.newBuilder().type(Event.MESSAGE_TYPE_SAVE_CUSTOM_SUCCESS).result(true).send();
                                }
                                break;
                            case 0x25://房间重命名上报
                                Log.d(TAG, "aaaaaaaaaa 房间重命名上报");
                                result = YxCloudMapDataParser.parseRoomNameData(robot.getMap().getRoom(), dst);
                                if (result.getCode() == ParseResult.MSG_PARSE_SUCCESS) {
                                    Log.d(TAG, "aaaaaaaaaa 房间重命名上报成功");
                                    Event.newBuilder().type(Event.MESSAGE_TYPE_RENAME_AREA_SUCCESS).result(true).send();
                                }
                                break;
                            case 0x27://设置房间清扫顺序上报
                                break;
                            case 0x2B:
                                if (dst[0] == 0x01) {
                                    Event.newBuilder().type(Event.MESSAGE_TYPE_SAVE_MULTI_MAP).result(true).send();
                                    Log.d(TAG, "save map success");
                                }
                                if (dst[0] == 0x00) {
                                    Event.newBuilder().type(Event.MESSAGE_TYPE_SAVE_MULTI_MAP).result(false).send();
                                    Log.d(TAG, "save map fail");
                                }
                                if (dst[0] == 0x02) {
                                    Event.newBuilder().type(Event.MESSAGE_TYPE_SAVE_MULTI_MAP).result(false).send();
                                    Log.d(TAG, "save map no room to save");
                                }
                                break;
                            case 0x2D:
                                if (dst[0] == 0x01) {
                                    Event.newBuilder().type(Event.MESSAGE_TYPE_DELETE_MULTI_MAP).result(true).send();
                                    Log.d(TAG, "delete map success");
                                }
                                if (dst[0] == 0x00) {
                                    Event.newBuilder().type(Event.MESSAGE_TYPE_DELETE_MULTI_MAP).result(false).send();
                                    Log.d(TAG, "delete map fail");
                                }
                                break;
                            case 0x2F:
                                Log.d(TAG, "aaaaaaaaaa setCurrent map");
                                if (dst[0] == 0x01) {
                                    Event.newBuilder().type(Event.MESSAGE_TYPE_USE_MAP).result(true).send();
                                    Log.d(TAG, "setCurrent map success");
                                    Log.d(TAG, "aaaaaaaaaa setCurrent map success");
                                }
                                if (dst[0] == 0x00) {
                                    Event.newBuilder().type(Event.MESSAGE_TYPE_USE_MAP).result(false).send();
                                    Log.d(TAG, "setCurrent map fail");
                                    Log.d(TAG, "aaaaaaaaaa setCurrent map fail");
                                }
                                break;
                            case (byte) 0x9B:
                                Log.d(TAG, "aaaaaaaaaa 障碍物/家具上报");
                                result = YxCloudMapDataParser.parseObstacleAndFurnitureData((YxCloudLaserMap) (robot.getMap().getMap()), robot.getMap().getFurniture(), robot.getMap().getObjectList(), dst);
                                if (result.getCode() == ParseResult.MSG_PARSE_SUCCESS) {
                                    Log.d(TAG, "aaaaaaaaaa 障碍物/家具上报上报解析成功");
                                    Event.newBuilder().type(Event.MSG_ROBOT_FURNITURE).result(true).content(robot.getMap().getFurniture()).send();
                                    Event.newBuilder().type(Event.MSG_ROBOT_OBJECT).result(true).content(robot.getMap().getObjectList()).send();
                                }
                                break;
                            default:
                                break;
                        }
                    }
                }
            }

            if (jsonObject.has(TuyaLaserConstant.MAP_ROOM_INFO)) {
                Log.d(TAG, "aaaaaaaaaa 房间信息上报");
                String roomInfo = jsonObject.getString(TuyaLaserConstant.MAP_ROOM_INFO);
                Log.d(TAG, "aaaaaaaaaa 房间信息上报===" + roomInfo);
                if (!roomInfo.equals(robot.getCacheData().getRoomListInfo())) {
                    Event.newBuilder().type(Event.MSG_ROBOT_ROOM).result(true).content(null).send();
                    Log.d(TAG, "aaaaaaaaaa 房间信息有修改");
                }
                robot.getCacheData().setRoomListInfo(roomInfo);
                //暂不解析
                /*byte[] bytes = StringUtils.hexToByte(roomInfo);
                List<byte[]> data = TuyaPublicMapDataParser.getCmdAndData(bytes);
                if (data != null && data.size() > 0) {
                    for (int i = 0; i < data.size(); i++) {
                        byte cmd = data.get(i)[0];
                        Log.d(TAG, "aaaaaaaaaa 房间信息上报 === cmd" + cmd);
                        byte[] dst = new byte[data.get(i).length - 1];
                        System.arraycopy(data.get(i), 1, dst, 0, dst.length);
                        switch (cmd) {
                            case 0x50://房间信息上报
                                Log.d(TAG, "aaaaaaaaaa 房间信息上报成功");
                                YxCloudMapDataParser.parseRoomListData(robot.getMap().getRoom(),dst);
                                break;
                        }
                    }
                }*/
            }

            if (jsonObject.has(TuyaLaserConstant.MAP_MAP_NAME_LIST)) {
                Log.d(TAG, "aaaaaaaaaa 多地图名字列表上报");
                String strData = jsonObject.getString(TuyaLaserConstant.MAP_MAP_NAME_LIST);
                Log.d(TAG, "aaaaaaaaaa 多地图名字列表上报===" + strData);
                byte[] bytes = StringUtils.hexToByte(strData);
                List<byte[]> data = YxCloudMapDataParser.getCmdAndData(bytes);
                if (data != null && data.size() > 0) {
                    for (int i = 0; i < data.size(); i++) {
                        byte cmd = data.get(i)[0];
                        Log.d(TAG, "aaaaaaaaaa 多地图名字列表上报===cmd" + cmd);
                        byte[] dst = new byte[data.get(i).length - 1];
                        System.arraycopy(data.get(i), 1, dst, 0, dst.length);
                        switch (cmd) {
                            case 0x54://多地图名字列表上报
                                Log.d(TAG, "aaaaaaaaaa 多地图名字列表上报成功");
                                List<MapNameParam> mapNameParams = YxCloudMapDataParser.parseMapNameListData(dst);
                                Event.newBuilder().type(Event.MESSAGE_TYPE_MULTI_MAP_NAMES).result(true).content(mapNameParams).send();
                                break;
                        }
                    }
                }
            }

            if (jsonObject.has(TuyaLaserConstant.EDGE_BRUSH)) {
                //边刷寿命
                int edge_brush = jsonObject.getInt(TuyaLaserConstant.EDGE_BRUSH) * 60;
                robot.getConsumption().setSideBrushLife(edge_brush);
                Event.newBuilder().result(true).type(Event.MESSAGE_TYPE_CONSUMPTION_UPDATE).content("X3").send();
            }
            if (jsonObject.has(TuyaLaserConstant.ROLL_BRUSH)) {
                //滚刷寿命
                int roll_brush = jsonObject.getInt(TuyaLaserConstant.ROLL_BRUSH) * 60;
                robot.getConsumption().setMainBrushLife(roll_brush);
                Event.newBuilder().result(true).type(Event.MESSAGE_TYPE_CONSUMPTION_UPDATE).content("X3").send();
            }
            if (jsonObject.has(TuyaLaserConstant.FILTER)) {
                //滤网寿命
                int strainerLife = jsonObject.getInt(TuyaLaserConstant.FILTER) * 60;
                robot.getConsumption().setStrainerLife(strainerLife);
                Event.newBuilder().result(true).type(Event.MESSAGE_TYPE_CONSUMPTION_UPDATE).content("X3").send();
            }
            if (jsonObject.has(TuyaLaserConstant.RAG_LIFE)) {
                //拖布寿命
                int mopLife = jsonObject.getInt(TuyaLaserConstant.RAG_LIFE) * 60;
                Log.d("disturb", "mopLife is " + mopLife);
                robot.getConsumption().setMopLife(mopLife);
                Event.newBuilder().result(true).type(Event.MESSAGE_TYPE_CONSUMPTION_UPDATE).content("X3").send();
            }
            if (jsonObject.has(TuyaLaserConstant.RAG_LIFE_RESET)) {
                //拖布重置
                boolean filterReset = jsonObject.getBoolean(TuyaLaserConstant.RAG_LIFE_RESET);
            }
            if (jsonObject.has("132")) {
                //扫拖模块滤网/水箱滤网(X3 X3S)
                int water_tank_filter = jsonObject.getInt("132") * 60;
                LogUtils.i("--扫拖模块滤网-1111---" + water_tank_filter);
                robot.getConsumption().setWaterTankFilterLife(water_tank_filter);
                Event.newBuilder().result(true).type(Event.MESSAGE_TYPE_CONSUMPTION_UPDATE).content("X3").send();
            }
            if (jsonObject.has(TuyaLaserConstant.SWITCH_DISTURB)) {
                //勿扰开关
                boolean quiteHourSwitch = jsonObject.getBoolean(TuyaLaserConstant.SWITCH_DISTURB);
                if (robot.getCacheData().isDisturbSwitch() != quiteHourSwitch) {
                    List<QuietHour> quietHourList = robot.getQuietHourList();
                    if (quietHourList.size() > 0) {
                        quietHourList.get(0).setEnable(quiteHourSwitch);
                    } else {
                        QuietHour quietHour = new QuietHour();
                        quietHour.setEnable(quiteHourSwitch);
                        quietHour.setRepeat(Arrays.asList(0, 1, 2, 3, 4, 5, 6));
                        quietHour.setStartTime(20 * 3600 + 0 * 60);
                        quietHour.setEndTime(8 * 3600 + 0 * 60);
                        quietHourList.add(quietHour);
                    }
                    Event.newBuilder().result(true).type(Event.MESSAGE_TYPE_GET_NO_DISTURB).content(quiteHourSwitch).send();
                    robot.getCacheData().setDisturbSwitch(quiteHourSwitch);
                }
            }
            if (jsonObject.has(TuyaLaserConstant.VOLUME_SET)) {
                //音量
                int volume = jsonObject.getInt(TuyaLaserConstant.VOLUME_SET);
                robot.getCleanSettings().setVolume(volume);
                Event.newBuilder().result(true).type(Event.MSG_ROBOT_SETTINGS).content(volume).send();
            }
            if (jsonObject.has(TuyaLaserConstant.BREAK_CLEAN)) {
                //断点续扫
                boolean breakpoint = jsonObject.getInt(TuyaLaserConstant.BREAK_CLEAN) == 0 ? false : true;
                robot.getCleanSettings().setBreakpointResume(breakpoint);
                Event.newBuilder().type(Event.MESSAGE_TYPE_BREAKPOINT_RESUME_SWITCH).result(true).send();
            }
            if (jsonObject.has(TuyaLaserConstant.FAULT)) {
                //故障告警 edge_sweep_fault - 边刷故障 middle_sweep_fault - 滚刷故障 left_wheel_fault - 左轮故障
                //right_wheel_fault - 右轮故障 garbage_box_fault - 尘盒故障 land_check_fault - 地检故障 collision_fault - 碰撞传感器故障
                int fault = jsonObject.getInt(TuyaLaserConstant.FAULT);
                //如果是错误状态 显示异常的条条， 如果不是 隐藏它
                //初始化故障信息
                robot.getRobotStatus().setError(fault + "");
//                robot.getRobotStatus().setWorkState(RobotStatus.STATE_ERROR_28);
                Event.newBuilder().type(Event.MESSAGE_TYPE_FAULT_STATUS).result(true).send();
            }
            if (jsonObject.has(TuyaLaserConstant.CLEAN_AREA_TOTAL)) {
                //总清扫面积
                int total_clean_area = jsonObject.getInt(TuyaLaserConstant.CLEAN_AREA_TOTAL);
                robot.getCleanStatistics().setHistoryArea(total_clean_area);
//                Log.d(TAG, "总清扫面积: " + total_clean_area);
                Event.newBuilder().type(Event.MESSAGE_TYPE_CLEAN_AREA_DURATION_FREQUENCY).result(true).send();
            }
            if (jsonObject.has(TuyaLaserConstant.CLEAN_COUNT_TOTAL)) {
                //总清扫次数
                int total_clean_count = jsonObject.getInt(TuyaLaserConstant.CLEAN_COUNT_TOTAL);
                robot.getCleanStatistics().setCleanCount(total_clean_count);
//                Log.d(TAG, "总清扫次数: " + total_clean_count);
                Event.newBuilder().type(Event.MESSAGE_TYPE_CLEAN_AREA_DURATION_FREQUENCY).result(true).send();
            }
            if (jsonObject.has(TuyaLaserConstant.CLEAN_TIME_TOTAL)) {
                //总清扫时间  涂鸦公版 时间单位是分钟min 转成秒s
                int total_clean_time = jsonObject.getInt(TuyaLaserConstant.CLEAN_TIME_TOTAL) * 60;
                robot.getCleanStatistics().setHistoryTime(total_clean_time);
//                Log.d(TAG, "总清扫时间: " + total_clean_time);
                Event.newBuilder().type(Event.MESSAGE_TYPE_CLEAN_AREA_DURATION_FREQUENCY).result(true).send();
            }
            if (jsonObject.has(TuyaLaserConstant.CLEAN_THE_LOCAL_TIME)) {
                //本地定时任务
                //AA000C3108010110101D00000202017D
                String local_time_task_data = jsonObject.getString(TuyaLaserConstant.CLEAN_THE_LOCAL_TIME);
                if (!local_time_task_data.equals(robot.getCacheData().getAppointment())) {
                    Log.d(TAG, "32 本地定时任务---- : " + local_time_task_data);
                    byte[] bytes = StringUtils.hex2byt1(local_time_task_data);
                    List<byte[]> data = YxCloudMapDataParser.getCmdAndData(bytes);
                    Log.d("x333", "data size is " + data.size());
                    if (data != null && data.size() > 0) {
                        for (int i = 0; i < data.size(); i++) {
                            String sumData = StringUtils.byte2hex(data.get(i));
                            Log.d("x333", "sumdata" + i + " is " + sumData);
                            byte cmd = data.get(i)[0];
                            Log.d("x333", "data" + i + "size is " + data.get(i).length + "=====" + "cmd is " + cmd);
                            byte[] dst = new byte[data.get(i).length - 1];
                            int start = 1;
                            System.arraycopy(data.get(i), 1, dst, 0, dst.length);
                            switch (cmd) {
                                case 0x31://本地定时任务
                                    List<Appointment> mList = new ArrayList<>();
                                    int appointmentNum = TuyaPublicMapDataParser.getValueFromData(dst, start, 1);
                                    Log.d("appointment", "appointmentNum is " + appointmentNum);
                                    start += 1;
                                    if (appointmentNum >= 1) {
                                        for (int num = 0; num < appointmentNum; num++) {
                                            Appointment appointment = new Appointment();
                                            int appointmentEnable = TuyaPublicMapDataParser.getValueFromData(dst, start, 1);
                                            start += 1;
                                            Log.d("appointment", "appointmentEnable is " + appointmentEnable);
                                            if (appointmentEnable == 1) {
                                                appointment.setEnable(true);
                                            } else if (appointmentEnable == 0) {
                                                appointment.setEnable(false);
                                            } else if (appointmentEnable == 2) {
                                                appointment.setAppointmentExpired(true);
                                                Log.d("appointment", "appointmentEnable is " + appointment.isAppointmentExpired());
                                            }
                                            //重复次数，按位取
                                            byte repeat = dst[start];
                                            start += 1;
                                            List<Integer> weeks = new ArrayList<>();
                                            String strRepeat = StringUtils.byteToBit(repeat);
                                            String[] strings = strRepeat.split("");
                                            for (int index = strings.length - 1; index > 0; index--) {
                                                if (strings[index].equals("1")) {
                                                    if (index != 1) {
                                                        weeks.add(8 - index);
                                                    } else {
                                                        weeks.add(0);
                                                    }

                                                }
                                            }

                                            Log.d("appointment", "strings size " + strings.length);
                                            appointment.setRepeat(weeks);
                                            Log.d("appointment", "repeat is " + strRepeat);
                                            int startHour = TuyaPublicMapDataParser.getValueFromData(dst, start, 1);
                                            Log.d("appointment", "startHour is " + startHour);
                                            start += 1;
                                            int startMin = TuyaPublicMapDataParser.getValueFromData(dst, start, 1);
                                            Log.d("appointment", "startMin is " + startMin);
                                            start += 1;
                                            appointment.setTime(startHour * 3600 + startMin * 60);
                                            appointment.initId();
                                            int roomCount = TuyaPublicMapDataParser.getValueFromData(dst, start, 1);
                                            Log.d("appointment", "roomCount is " + roomCount);
                                            start += 1;
                                            if (roomCount == 0) {
                                                Log.d("appointment", "dst len is " + dst.length);
                                                Log.d("appointment", "start  is " + start);
                                                CleanParam param = new CleanParam();
                                                if (start >= dst.length) {
                                                    break;
                                                }
                                                int workMode = TuyaPublicMapDataParser.getValueFromData(dst, start, 1);
                                                appointment.setWorkMode(workMode);
                                                appointment.setCleanMode(0);
                                                Log.d("appointment", "workMode is " + workMode);
                                                start += 1;

                                                int suction = TuyaPublicMapDataParser.getValueFromData(dst, start, 1);
                                                param.suction = suction;
                                                start += 1;
                                                Log.d("appointment", "suction is " + suction);
                                                int humidity = TuyaPublicMapDataParser.getValueFromData(dst, start, 1);
                                                param.humidity = humidity;
                                                start += 1;
                                                Log.d("appointment", "humidity is " + humidity);
                                                int cleanTimes = TuyaPublicMapDataParser.getValueFromData(dst, start, 1);
                                                start += 1;
                                                Log.d("appointment", "cleanTimes is " + cleanTimes);
                                                param.cleanTimes = cleanTimes;
                                                appointment.setCleanParam(param);
                                            } else if (roomCount > 0) {
                                                RoomCleanParam param = new RoomCleanParam();
                                                appointment.setCleanMode(1);
                                                List<Integer> roomIds = new ArrayList<>();
                                                for (int j = 0; j < roomCount; j++) {
                                                    int roomId = TuyaPublicMapDataParser.getValueFromData(dst, start, 1);
                                                    roomIds.add(roomId);
                                                    Log.d("appointment", "roomId is " + roomId);
                                                    start += 1;
                                                }
                                                param.setRoomIds(roomIds);
                                                int workMode = TuyaPublicMapDataParser.getValueFromData(dst, start, 1);
                                                appointment.setWorkMode(workMode);
                                                Log.d("appointment", "workMode is " + workMode);
                                                start += 1;

                                                int suction = TuyaPublicMapDataParser.getValueFromData(dst, start, 1);
                                                param.suction = suction;
                                                Log.d("appointment", "suction is " + suction);
                                                start += 1;
                                                int humidity = TuyaPublicMapDataParser.getValueFromData(dst, start, 1);
                                                param.humidity = humidity;
                                                Log.d("appointment", "humidity is " + humidity);
                                                start += 1;
                                                int cleanTimes = TuyaPublicMapDataParser.getValueFromData(dst, start, 1);
                                                param.cleanTimes = cleanTimes;
                                                start += 1;
                                                Log.d("appointment", "cleanTimes is " + cleanTimes);
                                                appointment.setCleanParam(param);
                                            }
                                            mList.add(appointment);
                                        }
                                    }
                                    robot.setAppointmentList(mList);
                                    Log.d("appointment", "mList size is " + mList.size());
                                    Log.d("appointment", "mList is " + new Gson().toJson(mList));

                                    Event.newBuilder().type(Event.MESSAGE_TYPE_QUERY_ALARM).result(true).content(mList).send();
                                    break;
                            }
                        }
                    }
                    robot.getCacheData().setAppointment(local_time_task_data);
                }
            }
            if (jsonObject.has(TuyaLaserConstant.DISTURB_TIME_SET)) {
                //勿扰时间设置
                //AA00083308141E00081E0093
                String disturb = jsonObject.getString(TuyaLaserConstant.DISTURB_TIME_SET);
                Log.d(TAG, " ： 33 勿扰时间设置---- : " + disturb);
                if (!robot.getCacheData().getDisturbTime().equals(disturb)) {
                    //String notDisturb = StringUtils.hexStringToString(disturb);
                    Log.d(TAG, "aaaaaaaaaa 勿扰" + disturb);
                    //AA00083308141E00081E0093
                    String strData = jsonObject.getString("33");
                    byte[] bytes = StringUtils.hex2byt1(strData);
                    List<byte[]> data = TuyaPublicMapDataParser.getCmdAndData(bytes);
                    if (data != null && data.size() > 0) {
                        for (int i = 0; i < data.size(); i++) {
                            byte cmd = data.get(i)[0];
                            byte[] dst = new byte[data.get(i).length - 1];
                            System.arraycopy(data.get(i), 1, dst, 0, dst.length);
                            Log.d(TAG, disturb + " ： 33 勿扰时间设置---- : " + cmd);
                            switch (cmd) {
                                case 0x33://勿扰模式
                                    List<QuietHour> quietHourList = robot.getQuietHourList();
                                    QuietHour quietHour;
                                    int startHour = TuyaPublicMapDataParser.getValueFromData(dst, 1, 1);
                                    int startMin = TuyaPublicMapDataParser.getValueFromData(dst, 2, 1);
                                    int endHour = TuyaPublicMapDataParser.getValueFromData(dst, 4, 1);
                                    int endMin = TuyaPublicMapDataParser.getValueFromData(dst, 5, 1);
                                    if (quietHourList.size() > 0) {
                                        quietHour = quietHourList.get(0);
                                    } else {
                                        quietHour = new QuietHour();
                                        quietHour.setEnable(false);
                                        quietHour.setRepeat(Arrays.asList(0, 1, 2, 3, 4, 5, 6));
                                        quietHourList.add(quietHour);
                                    }
                                    quietHour.setStartTime(startHour * 3600 + startMin * 60);
                                    quietHour.setEndTime(endHour * 3600 + endMin * 60);
                                    LogUtils.i("disturb: " + "startHour: " + startHour + " startMin: " + startMin);
                                    LogUtils.i("disturb: " + "endHour: " + endHour + " endMin: " + endMin);
                                    Event.newBuilder().type(Event.MESSAGE_TYPE_GET_NO_DISTURB).result(true).content(quietHourList).send();
                                    break;
                            }
                        }
                    }
                    robot.getCacheData().setDisturbTime(disturb);
                }
            }
            if (jsonObject.has(TuyaLaserConstant.DEVICE_INFO)) {
                String deviceInfo = jsonObject.getString(TuyaLaserConstant.DEVICE_INFO);
                JSONObject deviceInfoJson = new JSONObject(deviceInfo);
                //设备信息
                if (deviceInfoJson.has("Device_SN")) {
                    String device_sn = deviceInfoJson.getString("Device_SN");
                    robot.getFirmwareInfo().setSn(device_sn);
                }
                if (deviceInfoJson.has("Firmware_Version")) {
                    String firmware_version = deviceInfoJson.getString("Firmware_Version");
                    robot.getFirmwareInfo().setCompileVerions(firmware_version);
                }
                if (deviceInfoJson.has("IP")) {
                    String Ip = deviceInfoJson.getString("IP");
                    robot.getFirmwareInfo().setIp(Ip);
                }
                if (deviceInfoJson.has("Mac")) {
                    String mac = deviceInfoJson.getString("Mac");
                    robot.getFirmwareInfo().setMac(mac);
                }
                if (deviceInfoJson.has("Module_UUID")) {
                    String module_uuid = deviceInfoJson.getString("Module_UUID");
                    robot.getFirmwareInfo().setUuid(module_uuid);
                }
                if (deviceInfoJson.has("WiFi_Name")) {
                    String wifi_name = deviceInfoJson.getString("WiFi_Name");
                    robot.getFirmwareInfo().setSsid(wifi_name);
                }
            }
            if (jsonObject.has(TuyaLaserConstant.VOICE_DATA)) {
                //当前使用语音包
                String currentLanguage = jsonObject.getString(TuyaLaserConstant.VOICE_DATA);
                LogUtils.i("35 当前使用语音包---- : " + currentLanguage);
                robot.getCleanSettings().setCurrentLanguage(currentLanguage);
            }
            if (jsonObject.has(TuyaLaserConstant.AUTO_BOOST)) {
                //地毯增压(公版)
                boolean auto_boost = jsonObject.getInt(TuyaLaserConstant.AUTO_BOOST) == 0 ? false : true;
                //                Log.d(TAG, "45 地毯增压---- : " + auto_boost);
                robot.getCleanSettings().setCarpetPressurize(auto_boost);
                Event.newBuilder().type(Event.MSG_ROBOT_SETTINGS).result(true).send();
            }
            if (jsonObject.has(TuyaLaserConstant.CUSTOM_MODE_SWITCH)) {
                //定制模式
                LogUtils.i("105 定制模式--aaaa-- : ");
                boolean custom_mode = jsonObject.getInt(TuyaLaserConstant.CUSTOM_MODE_SWITCH) == 0 ? false : true;
                LogUtils.i("105 定制模式---- : " + custom_mode);
                robot.getCleanSettings().setCustomSwitch(custom_mode);
                Event.newBuilder().type(Event.MSG_ROBOT_SETTINGS).result(true).send();
            }
            if (jsonObject.has("117")) {
                //尘盒状态  true:已安装 false:未安装
                boolean dustBoxStatus = jsonObject.getBoolean("117");
                robot.getCleanSettings().setDustBoxStatus(dustBoxStatus);
                Event.newBuilder().type(Event.MESSAGE_TYPE_TANK_DUSTBOX_STATUS).send();
            }
            if (jsonObject.has("118")) {
                //水箱状态  true:已安装 false:未安装
                boolean tankStatus = jsonObject.getBoolean("118");
                robot.getCleanSettings().setTankStatus(tankStatus);
                Event.newBuilder().type(Event.MESSAGE_TYPE_TANK_DUSTBOX_STATUS).send();
            }
            if (jsonObject.has("135")) {
                //灯光（青春版）
                boolean lightSwitch = jsonObject.getBoolean("135");
                robot.getCleanSettings().setLightSwitch(lightSwitch);
            }
            if (jsonObject.has("185")) {
                //多楼层地图
                boolean openMultiMap = jsonObject.getBoolean("185");
                if (robot.getCacheData().isMultiMapSwitchOpen() != openMultiMap) {
                    robot.getCacheData().setMultiMapSwitchOpen(openMultiMap);
                    robot.getCleanSettings().setOpenMultiMap(openMultiMap);
                    Event.newBuilder().type(Event.MSG_ROBOT_MULTI_MAP).result(true).send();
                }
            }
            if (jsonObject.has("37")) {
                /*集尘频率设置 0 - 关闭自动集尘 1 - 1次 2 - 2次 3 - 3次*/
                int dust_collection_num = jsonObject.getInt("37");
                robot.getCleanSettings().setAutoDust(dust_collection_num + "");
                //Event.newBuilder().type(Event.MESSAGE_TYPE_DUST_COLLECTION_NUM).content(dust_collection_num).send();
            }
            if (jsonObject.has("150")) {
                String tmalDeviceId = jsonObject.getString("150");
                robot.setTmalDeviceId(tmalDeviceId);
            }
            if (jsonObject.has("connected")) {
                //是否在线 //全局监听设备在线离线状态 在到BaseActivity 中监听
                String connected = jsonObject.getString("connected");
                if ("true".equals(connected)) {
                    robot.setOnline(true);
                    Event.newBuilder().type(Event.MESSAGE_TYPE_CONNECTED).result(true).content(true).send();
                } else {
                    robot.setOnline(false);
                    Event.newBuilder().type(Event.MESSAGE_TYPE_CONNECTED).result(true).content(false).send();
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    protected static void parseState(int state, Robot robot) {
        LogUtils.i("robot_state =state=====" + state);
        RobotStatus status = robot.getRobotStatus();
        status.setSubState(RobotStatus.SUBSTATE_NONE);
        if (12 == state) {
            //休眠
            status.setWorkState(RobotStatus.STATE_DORMANT);
        } else if (0 == state) {
            //待机
            status.setWorkState(RobotStatus.STATE_STANDBY);
        } else if (1 == state || 4 == state) {
            //清扫
            status.setWorkState(RobotStatus.STATE_WORKING);
            status.setWorkMode(RobotStatus.MODE_AUTO_CLEAN);
        } else if (5 == state) {
            //暂停
            status.setWorkState(RobotStatus.STATE_PAUSE);
        } else if (16 == state) {
            //选区清扫
            status.setWorkState(RobotStatus.STATE_WORKING);
            status.setWorkMode(RobotStatus.MODE_ROOM_CLEAN);
        } else if (2 == state) {
            //区域扫
            status.setWorkState(RobotStatus.STATE_WORKING);
            status.setWorkMode(RobotStatus.MODE_CUSTOM_CLEAN);
        } else if (3 == state) {
            //局部清扫
            status.setWorkState(RobotStatus.STATE_WORKING);
            status.setWorkMode(RobotStatus.MODE_SPOT_CLEAN);
        } else if (9 == state) {
            //回充中
            status.setWorkState(RobotStatus.STATE_WORKING);
            status.setWorkMode(RobotStatus.MODE_RECHARGE);
        } else if ("mop".equals(state)) {
            //拖地
            status.setWorkState(RobotStatus.STATE_WORKING);
            status.setWorkMode(RobotStatus.MODE_MOP);
        } else if (13 == state) {
            //故障
            status.setWorkState(RobotStatus.STATE_ERROR);
        } else if ("seek_dust_bucket".equals(state)) {
            //寻找集尘桶中
            status.setWorkState(RobotStatus.STATE_DUST_COLLECTION_PUBLIC);
        } else if (18 == state || "collecting_dust".equals(state)) {
            //集尘中  collecting_dust 这个字段适配LF27
            status.setWorkState(RobotStatus.STATE_DUST_COLLECTION);
        } else if (10 == state || 11 == state) {
            //充电中
            status.setWorkState(RobotStatus.STATE_CHARGING);
        } else if (20 == state) {
            // 清洗拖布中
            status.setWorkState(RobotStatus.STATE_CLEANING_MOP);
        } else if (21 == state) {
            // 风干拖布中 21
            status.setWorkState(RobotStatus.STATE_DRYING_MOP);
        } else if (19 == state) {
            // 返回基站中
            status.setWorkState(RobotStatus.STATE_GOTO_BS);
        } else if (6 == state) {
            // 前往目标点中 状态限制】同清扫
            status.setWorkState(RobotStatus.STATE_WORKING);
            status.setSubState(RobotStatus.SUBSTATE_WORKING_GOTO_POS);
        } else if (7 == state) {
            // 目标点已到达 状态限制】同待机
            status.setWorkState(RobotStatus.STATE_WORKING);
            status.setSubState(RobotStatus.SUBSTATE_WORKING_POS_ARRIVED);
        } else if (8 == state) {
            // 目标点不可达 状态限制】同待机
            status.setWorkState(RobotStatus.STATE_STANDBY);
            status.setSubState(RobotStatus.SUBSTATE_WORKING_POS_UNARRIVE);
        } else if (15 == state) {
            // 遥控模式 状态限制】同工作中
            status.setWorkState(RobotStatus.STATE_WORKING);
            status.setWorkMode(RobotStatus.MODE_CONTROL);
        } else if (17 == state) {
            // 重定位中 状态限制】同全屋/自定义...清扫状态
            status.setWorkState(RobotStatus.STATE_WORKING);
            status.setSubState(RobotStatus.SUBSTATE_WORKING_REPOSITING);
        } else if ("creating_map".equals(state)) {
            // 建图中
            status.setWorkState(RobotStatus.STATE_WORKING);
            status.setSubState(RobotStatus.SUBSTATE_WORKING_CREATINGMAP);
        } else if (22 == state) {
            // 注水中
            status.setWorkState(RobotStatus.STATE_WATER_INJECTION);
        }
        LogUtils.d("aaaaaaaaaa 状态-- 发送-- MSG_ROBOT_STATE: ");
        Event.newBuilder().type(Event.MSG_ROBOT_STATE).send();
    }

}
